package com.miracle.basemvp.base.delegate;

import android.app.Activity;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

/**
 * FragmentController.java
 * (c)2018 AIR Times Inc. All rights reserved.
 * fragment控制器
 *
 * @author WangJQ
 * @version 1.0
 * @date 2018/7/11 9:15
 * @see com.miracle.basemvp.base.delegate
 */
public class FragmentController {

    public Fragment mPreFragment;
    public Fragment mCurrFragment;
    public Context mContext;
    public FragmentManager mFragmentManager;

    public FragmentController(FragmentManager fragmentManager) {
        mFragmentManager = fragmentManager;
    }

    /**
     * @param containerId FrameLayoutId
     * @param fragment
     */
    public void showOrHideFragment(int containerId, Fragment fragment) {
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        mPreFragment = mCurrFragment;
        mCurrFragment = fragment;
        if (fragment != null && fragment.isAdded()) {
            if (fragment.isHidden()) {
                transaction.show(fragment);
                transaction.commitAllowingStateLoss();
            }
        } else {
            transaction.add(containerId, fragment, fragment.getTag());
//            transaction.addToBackStack(null);
            transaction.commitAllowingStateLoss();
        }
        if (mPreFragment != null) {
            transaction.hide(mPreFragment);
//            transaction.commit();
        }
    }

}
